from datetime import datetime, timedelta
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request

from sanren.utils import get_current_active_user, Helper
from application.http import models
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.http import schemas
from application.config import appSettings


router = APIRouter(prefix='/brand/accounts', tags=['Brand'])
module_name = '品牌商模块 - 品牌商用户'


@router.get('', response_model=schemas.BaseApiListOut)
async def get_brand_users(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    brand_id: Optional[int] = None,
    code: Optional[str] = None,
    keyword: Optional[str] = None,
):
    """
        品牌商用户列表
    """

    objs = OemModel.BrandUser.with_('brand')

    if brand_id:
        objs = objs.where('brand_id', brand_id)

    if code:
        objs = objs.where('code', code)

    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'brand_id', 'like', f'%{keyword}%'
            ).or_where(
                'name', 'like', f'%{keyword}%'
            ).or_where(
                'username', 'like', f'%{keyword}%'
            ).or_where(
                'email', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.post('', response_model=schemas.BaseApiOut)
async def add_brand_user(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    post: ApiSchemas.brand.BrandUserCreate,
):
    """
        添加品牌商 商户号
    """

    company = OemModel.BrandUser.where('brand_id', post.brand_id).where('type', 1).first()
    if company:
        return schemas.BaseApiOut(code=1, message='此品牌商:商户号已存在')
    if post.password != post.comfirm_password:
        return schemas.BaseApiOut(code=1, message='密码不一致')
    if post.username == '':
        return schemas.BaseApiOut(code=1, message='用户名不能为空')

    try:
        obj = OemModel.BrandUser.create(
            type=post.type,
            code=post.code,
            brand_id=post.brand_id,
            name=post.name,
            email=post.email,
            username=post.username,
            is_active=post.is_active,
            password_hash=OemModel.BrandUser.get_password_hash(post.password),
        )

        print('操作成功:', obj.fresh().id)
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.put('/{id}', response_model=schemas.BaseApiOut)
async def edit_brand_user(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: ApiSchemas.brand.BrandUserCreate,
    id: int,
):
    """
        编辑品牌商 商户号
    """

    obj = OemModel.BrandUser.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此品牌商:商户号用户不存在')

    if post.is_setpass == 1 and post.password != post.comfirm_password:
        return schemas.BaseApiOut(code=1, message='密码不一致')

    try:
        # 更新企业
        obj.name = post.name
        obj.email = post.email
        obj.is_active = post.is_active
        if post.is_setpass == 1:
            obj.set_password(post.password)
        obj.save()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}
